package com.aiton.bamin.bamindaijiadrier.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.aiton.administrator.shane_library.shane.utils.GsonUtils;
import com.aiton.administrator.shane_library.shane.widget.SingleBtnDialog;
import com.aiton.bamin.bamindaijiadrier.R;
import com.aiton.bamin.bamindaijiadrier.constant.Constant;
import com.aiton.bamin.bamindaijiadrier.model.Sms;
import com.aiton.bamin.bamindaijiadrier.model.User;
import com.aiton.bamin.bamindaijiadrier.model.Wallet;
import com.aiton.bamin.bamindaijiadrier.widget.OnPasswordInputFinish;
import com.aiton.bamin.bamindaijiadrier.widget.PasswordView;
import com.blankj.utilcode.utils.EncryptUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import cz.msebera.android.httpclient.Header;

public class WalletActivity extends ZjbBaseActivity implements View.OnClickListener {

    private User mUser;
    private TextView mTv_money;
    private PopEnterPassword mPopEnterPassword;
    private Wallet.DatasBean mDatas;
    private BroadcastReceiver recevier = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(TextUtils.equals(action,Constant.BROADCASTCODE.WALLET)){
                showNotecaseInfo();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wallet);
        showLoadingDialog();
        init();

    }

    @Override
    protected void initData() {
        showNotecaseInfo();
        isPassWord();

    }

    /**
     * 钱包信息
     */
    private void showNotecaseInfo() {
        String url = Constant.Url.GET_NOTECASE_BY_DRIVER_ID;
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("driverId", mUser.getDatas().getId());
        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String s = new String(responseBody);
                Log.e("WalletActivity", "钱包信息: --->>" + s);
                try {
                    Wallet wallet = GsonUtils.parseJSON(s, Wallet.class);
                    if (wallet.getStatus() == 0) {
                        mDatas = wallet.getDatas();
                        mTv_money.setText(mDatas.getNotecase()+"");
                    }
                } catch (Exception e) {
                    Log.e("WalletActivity", "解析失败");
                }
                cancelLoadingDialog();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Log.e("WalletActivity", "请求失败");
                Toast.makeText(WalletActivity.this, "数据请求失败", Toast.LENGTH_SHORT).show();
                cancelLoadingDialog();

            }
        });

    }

    @Override
    protected void initViews() {

    }

    @Override
    protected void setListeners() {
        findViewById(R.id.imageView_back).setOnClickListener(this);
//        findViewById(R.id.textView_recharge).setOnClickListener(this);
        findViewById(R.id.textView_advance).setOnClickListener(this);
        findViewById(R.id.tv_bill).setOnClickListener(this);

    }

    @Override
    protected void initSP() {

    }

    @Override
    protected void initIntent() {
        Intent intent = getIntent();
        mUser = (User) intent.getSerializableExtra(Constant.INTENT_KEY.USER);
        if (mUser == null) {
            final SingleBtnDialog singleBtnDialog = new SingleBtnDialog(this, "用户信息出错", "确定");
            singleBtnDialog.setClicklistener(new SingleBtnDialog.ClickListenerInterface() {
                @Override
                public void doWhat() {
                    finishTo();
                    singleBtnDialog.dismiss();
                }
            });
            singleBtnDialog.show();
        }
    }

    @Override
    protected void findID() {
        mTv_money = (TextView) findViewById(R.id.tv_money);

    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.imageView_back:
                finishTo();
                break;
            case R.id.tv_bill:
                intent.setClass(this, BillActivity.class);
                intent.putExtra(Constant.INTENT_KEY.WALLET,mDatas);
                startActivityTo(intent);
                break;
            case R.id.textView_advance:
                intent.setClass(this,WalletAdvanceActivity.class);
                intent.putExtra(Constant.INTENT_KEY.WALLET,mDatas);
                startActivityTo(intent);

                break;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.BROADCASTCODE.WALLET);
        registerReceiver(recevier,intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(recevier);
    }

    /**
     * 判断是否有设置密码
     */
    public void isPassWord() {
        String url = Constant.Url.IS_PASSWORD;
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("driverId", mUser.getDatas().getId());
        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String s = new String(responseBody);
                Log.e("WalletActivity", "判断是否有设置密码: --->>" + s);
                try {
                    Sms sms = GsonUtils.parseJSON(s, Sms.class);
                    if (sms.getStatus() == 1) {
                        cancelLoadingDialog();

                        Toast.makeText(WalletActivity.this, sms.getMes(), Toast.LENGTH_SHORT).show();
                        mPopEnterPassword = new PopEnterPassword(WalletActivity.this, "设置", "请输入密码");

                        // 显示窗口
                        mPopEnterPassword.showAtLocation(WalletActivity.this.findViewById(R.id.activity_wallet),
                                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置
                    }

                } catch (Exception e) {
                    Log.e("WalletActivity", "解析失败");
                    cancelLoadingDialog();

                }


            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Log.e("WalletActivity", "请求失败");
                Toast.makeText(WalletActivity.this, "数据请求失败", Toast.LENGTH_SHORT).show();

            }
        });
    }

    /**
     * 输入支付密码
     *
     * @author lining
     */
    public class PopEnterPassword extends PopupWindow {

        private PasswordView pwdView;

        private View mMenuView;

        private Activity mContext;


        public PopEnterPassword(final Activity context, String way, String money) {

            super(context);

            this.mContext = context;

            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            mMenuView = inflater.inflate(R.layout.pop_enter_password, null);

            pwdView = (PasswordView) mMenuView.findViewById(R.id.pwd_view);

            TextView mTv_way = (TextView) mMenuView.findViewById(R.id.tv_way);
            final TextView mTv_money = (TextView) mMenuView.findViewById(R.id.tv_money);

            mTv_way.setText(way);
            mTv_money.setText(money);
            //添加密码输入完成的响应
            pwdView.setOnFinishInput(new OnPasswordInputFinish() {

                @Override
                public void notTheSame(String password) {
                    mTv_money.setTextSize(20);
                    mTv_money.setText("两次输入密码不一致,请重新输入");

                }

                @Override
                public void theSamePassword(String password) {

                    setPassWord(password);
                }

                @Override
                public void inputAgain(String password) {
                    mTv_money.setText("再次输入密码");

                }
            });


            // 监听X关闭按钮
            pwdView.getImgCancel().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });

            // 监听键盘上方的返回
            pwdView.getVirtualKeyboardView().getLayoutBack().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });

            // 设置SelectPicPopupWindow的View
            this.setContentView(mMenuView);
            // 设置SelectPicPopupWindow弹出窗体的宽
            this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            // 设置SelectPicPopupWindow弹出窗体的高
            this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            // 设置SelectPicPopupWindow弹出窗体可点击
            this.setFocusable(true);
            // 设置SelectPicPopupWindow弹出窗体动画效果
            this.setAnimationStyle(R.style.pop_add_ainm);
            // 实例化一个ColorDrawable颜色为半透明
            ColorDrawable dw = new ColorDrawable(0x66000000);
            // 设置SelectPicPopupWindow弹出窗体的背景
            this.setBackgroundDrawable(dw);

        }
    }

    /**
     * 设置密码
     *
     * @param password
     */
    private void setPassWord(String password) {
        showLoadingDialog();
        String url = Constant.Url.START_NOTECASE;
        String password4Encrypt = EncryptUtils.encryptSHA256ToString(password);

        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("driverId", mUser.getDatas().getId());
        params.put("password", password4Encrypt);

        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String s = new String(responseBody);
                Log.e("WalletActivity", "设置密码: --->>" + s);

                try {
                    Sms sms = GsonUtils.parseJSON(s, Sms.class);
                    if (sms.getStatus() == 0) {
                        Toast.makeText(WalletActivity.this, "密码设置成功", Toast.LENGTH_SHORT).show();
                        mPopEnterPassword.dismiss();
                    } else {
                        Toast.makeText(WalletActivity.this, "密码设置失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    Toast.makeText(WalletActivity.this, "数据解析失败", Toast.LENGTH_SHORT).show();
                }
                cancelLoadingDialog();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Toast.makeText(WalletActivity.this, "数据请求失败", Toast.LENGTH_SHORT).show();
                cancelLoadingDialog();

            }
        });
    }
}
